<template>
    <div class="main-register">
        <center class="title">Sign Up</center>
        <template v-for="(item,index) in steps">
            <component :is="item.template" v-if="index == step" :key="index" v-model:form="formData" ></component>
        </template>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, provide  } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Step1 from '../components/register/setp1.vue'
import Step2 from '../components/register/setp2.vue'
import Step3 from '../components/register/setp3.vue'
import { Notify, Toast } from 'vant'

const route = useRoute()

const router = useRouter()

const steps: Array<{template: any}> = [
    {
        template: Step1
    },{
        template: Step2
    },{
        template: Step3
    }
]

const step = ref(0)

const formData: {username: string, phoneNum: string, countryid: string, password: string, confirmPwd: string, code: string} = reactive({
    username: '',
    phoneNum: '',
    countryid: '',
    password: '',
    confirmPwd: '',
    code: ''
})

const onNext = () => {
    step.value++
    router.push({name: 'Register', query: {step: step.value}})
}

const onSubmit = () => {
    const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
        message: 'Loading...'
    });
    setTimeout(()=>{
        toast.clear()
        Notify({ type: 'success', message: 'register was successful', onClose: ()=>{
            router.replace({name: 'Login'})
        }});
    }, 3000)
}

const onFailed = (err: any) =>{
    Notify({ type: 'warning', message: err.errors[0].message });
}

provide('onFailed', onFailed)
provide('onNext', onNext)
provide('onSubmit', onSubmit)

watch([route], ()=>{
    step.value = Number.parseInt((route.query.step || '0') as string)
})

</script>

<style lang="less" scoped>
.main-register {
    .title {
        font-weight: bold;
        font-size: 24px;
        line-height: 41px;
        letter-spacing: 0.41px;
        color: #FF5E00;
    }
}
</style>
